package com.fate.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fate.constant.AuthConstant;
import com.fate.domain.LoginUser;
import com.fate.domain.SysLoginUser;
import com.fate.mapper.LoginUserMapper;
import com.fate.mapper.SysLoginUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysLoginUserMapper sysLoginUserMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoginUserMapper loginUserMapper;

    /**
     * 微信小程序的appid
     */
    @Value(("${wx.appid}"))
    private String appid;
    /**
     * 微信小程序的appsecret
     */
    @Value(("${wx.appsecret}"))
    private String appsecret;
    /**
     * 微信小程序的tokenurl
     */
    @Value("${wx.tokenurl}")
    private String tokenurl;
    /**
     * 这个就是登录方法
     * 两套前端
     * 后台管理系统
     * 前台商城
     *
     * @param
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //拿到requset
        ServletRequestAttributes requestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //拿到header标识
        String loginType = request.getHeader(AuthConstant.LOGIN_TYPE);
        if (StringUtils.isEmpty(loginType)){
            //前台在开发阶段 忘记写了 或者有人恶意访问
            loginType = AuthConstant.SYS_USER;
        }
        switch (loginType){
            case AuthConstant.SYS_USER:
                //查询后台的表
                //因为我们的一个多租户 每个商家的标记也不一样
                SysLoginUser sysLoginUser = sysLoginUserMapper.selectOne(new LambdaQueryWrapper<SysLoginUser>()
                        .eq(SysLoginUser::getUsername, username)
                );
                if (!ObjectUtils.isEmpty(sysLoginUser)){
                    //权限
                   List<String> auths =  sysLoginUserMapper.findAuthById(sysLoginUser.getUserId());
                    sysLoginUser.setAuths(auths);
                }
                return sysLoginUser;
            case AuthConstant.MEMBER:
                // 因为前台是微信小程序 把appid secret code 发一个get请求到微信服务器 微信服务器返回一个openid
                //tokenurl %s %s  %s
                String format = String.format(tokenurl, appid, appsecret, username);
                String wxJson = restTemplate.getForObject(format, String.class);
                //转成json对象
                JSONObject jsonObject = JSON.parseObject(wxJson);
                String openid = jsonObject.getString("openid");
                if (StringUtils.hasText(openid)){
                    //说明微信那边授权成功 我们需要吧这个openId保存起来 返回微信小程序一个jwt
                    //查询数据库
                    LoginUser user = loginUserMapper.selectById(openid);
                    if (ObjectUtils.isEmpty(user)){
                      user = createUser(openid);
                    }
                    return user;
                }
        }
        return null;
    }

    /**
     * 创建前台用户
     * @param openid
     * @return
     */
    private LoginUser createUser(String openid) {
        LoginUser user = new LoginUser();
        user.setUserId(openid);
        user.setUserRegtime(new Date());
        user.setModifyTime(new Date());
        user.setStatus(1);
        user.setScore(0);
        //获取ip
       ServletRequestAttributes requestAttributes =  (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteHost();
        user.setUserLastip(ip);
        user.setUserRegip(ip);
        //插入数据库
        loginUserMapper.insert(user);
        return user;
    }


}
